package com.liushuai.eas.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liushuai.eas.common.Result;
import com.liushuai.eas.pojo.Classroom;
import com.liushuai.eas.service.BuildingImp;
import com.liushuai.eas.service.ClassroomImp;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/classroom")
public class ClassroomController {

    @Resource
    private ClassroomImp classroomImp;

    @Resource
    private BuildingImp buildingImp;

    @PostMapping
    public Result<?> add(@RequestBody Classroom classroom){

        //插入classroom数据库
        if (classroomImp.insert(classroom)!=1)
            return Result.fail(classroom);

        return Result.success(classroom);
    }

    @PutMapping
    public Result<Classroom> update(@RequestBody Classroom classroom){
        if (classroomImp.updateById(classroom)!=1)
            return Result.fail(classroom);
        return Result.success(classroom);
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){

        List<Classroom> classroomList;
        int total = 0;
        HashMap<String,Object> map = new HashMap<String,Object>();

        if (search.isEmpty()){
            classroomList = classroomImp.queryClassroomList((pageNum - 1) * pageSize,  pageSize);
            total = classroomImp.queryTotal();
        }else {
            classroomList = classroomImp.queryClassroomListBySearch((pageNum - 1) * pageSize, pageSize,search);
            total = classroomImp.queryTotalBySearch(search);
        }

        for(Classroom classroom : classroomList){
            classroom.setBuilding(buildingImp.selectOne(classroom.getBuildingId()));
        }

        map.put("records",classroomList);
        map.put("total",total);
        map.put("pageSize",pageSize);
        return Result.success("数据加载成功",map);
    }

    @DeleteMapping
    public Result<Classroom> delete(@RequestBody Classroom classroom){
        if (classroomImp.deleteById(classroom)!=1)
            return Result.fail(classroom);
        return Result.success(classroom);
    }

    @GetMapping("/selectAll")
    public Result<List<Classroom>> selectAll(){

        List<Classroom> classroomList = classroomImp.selectList(new QueryWrapper<>());

        return Result.success(classroomList);
    }

}
